<div class="layui-card-header layui-card">
    <span class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">首页</a>
        <a><cite class="cite1">资金归集</cite></a>
        <a><cite class="cite2">营销红包分账</cite></a>
        <a><cite>创建红包</cite></a>
    </span>
</div>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">账号模板列表</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-row">
                    <div class="layui-form" style="float:right;">
                        <div class="layui-form-item" style="margin:0;">
                            <div class="layui-input-inline">
                            </div>
<!--                            <a id="search" class="layui-btn" data-type="reload"><i class="layui-icon layui-icon-search"></i>搜索</a>-->
                        </div>
                    </div>
                </div>
                <div class="layui-row">
                    <div class="layuiAdmin-btns" style="margin-bottom: 10px;"></div>
                </div>
                <table id="cList" lay-filter="cList"></table>


            </div>
        </div>
    </div>
</div>
<script>

    layui.use(['table','util', 'form', 'laydate', 'util'], function(){
        var table = layui.table
            ,$ = layui.$
            ,form = layui.form
            ,element = layui.element
            ,laydate = layui.laydate
            ,util = layui.util
            ,admin = layui.admin;

        element.render('breadcrumb', 'breadcrumb');//渲染导航信息

        var router = layui.router();
        var payPassageId = router.search.payPassageId;

        var tplEdit = function(d){
            if(d.ifTypeCode == 'alipay'){ //只有支付宝类型才可创建红包
                return "<a class='layui-btn layui-btn-danger layui-btn-xs' lay-event='createRedCash'><i class='layui-icon layui-icon-add-1'></i>创建红包</a>";
            }
            return '';
        };

        var tplStatus = function(d){
            if(d.status == 0) {
                return "关闭";
            }else if(d.status == 1) {
                return "<span style='color: green'>开启</span>";
            }
        };

        //点击【创建红包】 弹层显示内容
        var createRedCashDivHtml = `
                <form class="layui-form center">
                <input hidden class="redCashPayAccountTemplateId"/>
                <div class="layui-form-item" style="margin-top:20px">
                    <label class="layui-form-label" style="width:130px;">红包名称：</label>
                    <div class="layui-input-inline" style="width: 392px;">
                        <input type="text" autocomplete="off" class="layui-input redCashCouponName" value="大吉大利">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:130px;">红包描述信息：</label>
                    <div class="layui-input-inline" style="width: 392px;">
                        <input type="text" autocomplete="off" class="layui-input redCashPrizeMsg" value="大吉大利领红包">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:130px;">红包开始/结束时间：</label>
                    <div class="layui-input-inline" style="width: 392px;">
                        <input class="layui-input redCashStartTime" type="text" style="width:150px;display: inline;" readonly> -
                        <input class="layui-input redCashEndTime" type="text" style="width:150px;display: inline;" readonly>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:130px;">单包最大金额（元）:</label>
                    <div class="layui-input-inline" style="width: 302px;">
                        <input type="text" class="layui-input redCashSingleMaxMoney layui-bg-gray" readonly value="200" />
                    </div>
                    <div class="layui-input-inline" style="width: 80px;">
                        <input type="checkbox" lay-filter="redCashChangeSingleMaxMoneyFilter" title="更改" lay-skin="primary" />
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:130px;">红包总金额（元）：</label>
                    <div class="layui-input-inline" style="width: 392px;">
                        <input type="text" class="layui-input redCashTotalMoney" />
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width:130px;">选择分账用户：</label>
                    <div class="layui-input-inline selectUserDiv" style="width: 392px; min-height: 120px">

                    </div>
                </div>


                <div class="layui-form-item" style="margin-top:30px">
                    <div class="layui-input-block" style="margin-left: 190px;">
                        <button type="button" class="layui-btn layui-btn-danger createRedCashAndPayBtn">创建并支付</button>
                    </div>
                </div>
            </form>
        `;

        //点击【创建并支付】弹层显示内容
        var toPayHtml = `
                <div class="layui-form-item" style="margin-top:20px; margin-bottom: 30px">

                    <div class="layui-form-item" style="margin-left:170px; margin-bottom: 20px;">
                        <label>请确认是否支付完成？</label>
                    </div>

                    <div class="layui-input-block">
                        <button type="button" class="layui-btn layui-btn-normal redCashPayFinishOrFail">
                            <i class="layui-icon layui-icon-ok-circle"></i>支付完成
                         </button>
                        <button type="button" class="layui-btn layui-btn-danger redCashPayFinishOrFail">
                            <i class="layui-icon layui-icon-about"></i>支付遇到问题
                        </button>
                    </div>
                </div>
        `;

        var thisLayerId = ""; //当前弹层ID
        var thisRedCashId = ""; //当前红包ID

        table.render({
            elem: '#cList'
            ,url: layui.setter.baseUrl + '/config/pay_interface_type/template/list'
            ,where: { access_token: layui.data(layui.setter.tableName).access_token, "belongInfoType" : 4}
            ,id: 'tableReload'
            ,cols: [[
                {field:'id', title: 'ID'}
                ,{field:'templateName',  title: '模板名称'}
                ,{field:'ifTypeCode', title: '接口类型代码'}
                ,{title: '已收款金额（元）', templet: '<div>{{ d.totalPaymentAmount / 100 }}</div>'}
                ,{title: '已分账金额（元）', templet: '<div>{{ d.totalCashAmount / 100 }}</div>'}
                ,{field:'status', title: '状态',templet: tplStatus }
                ,{field: 'createTime', width: 200, title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
                ,{width: 120, title: '操作', templet: tplEdit }
            ]]
            ,page: true
            ,skin: 'line'
        });

        //监听工具条
        table.on('tool(cList)', function(obj){
            var data = obj.data;
            if(obj.event === 'createRedCash'){ //点击【创建红包】事件

                //打开弹层
                thisLayerId = layer.open({ type: 1, area: ['600px', 'auto'], title: '创建红包', content: createRedCashDivHtml });
                //默认时间为：当前时间 - 当前时间+5min
                var nowDateTime = new Date().getTime();
                laydate.render({elem: '.redCashStartTime', type: 'datetime', value: util.toDateString(nowDateTime, 'yyyy-MM-dd HH:mm:ss')});
                laydate.render({elem: '.redCashEndTime', type: 'datetime', value: util.toDateString((nowDateTime + (5*60*1000)), 'yyyy-MM-dd HH:mm:ss')});
                //查询最新的可用分账用户数量
                admin.req({
                    type: 'get',
                    url: layui.setter.baseUrl + '/alipayCashUser/countByAvailable',
                    error: function(err){layer.alert(err);},
                    success: function(res){

                        var divHtml = '<input type="checkbox" lay-filter="selectAllUserFilter" title="全选" lay-skin="primary" /><br/>';

                        $.each(res.data, function(){
                            var titleHtml = '' + this.ps.mgrUserName + '<span style=\'color:red\'>(今总:'+this.ps.sumToday/100+'|昨总:'+this.ps.sumYesterday/100+'|分账用户:'+this.ps.count+')</span>';
                            divHtml +=' <input name="selectUserItem" lay-skin="primary" lay-filter="selectUserItemFilter" type="checkbox" value="'+this.createUserId+'" title="'+titleHtml+'"  />';
                        });

                        $(".selectUserDiv").append(divHtml);
                        form.render();
                    }
                });
                $('.redCashPayAccountTemplateId').val(data.id);

            }
        });


        $("body").off('click', '.createRedCashAndPayBtn'); //先移除 在创建； 避免按钮触发多次
        $("body").off('click', '.redCashPayFinishOrFail');
        $("body").on('click', '.createRedCashAndPayBtn', function(){ //点击【创建并支付】按钮点击事件

            var redCashCouponName = $('.redCashCouponName').val(); //红包名称
            var redCashPrizeMsg = $('.redCashPrizeMsg').val(); //红包描述
            var redCashSingleMaxMoney = $('.redCashSingleMaxMoney').val(); //单包最大金额
            var redCashTotalMoney = $('.redCashTotalMoney').val(); //红包总金额
            var redCashStartTime = $('.redCashStartTime').val(); //红包开始时间
            var redCashEndTime = $('.redCashEndTime').val(); //红包结束时间
            var redCashPayAccountTemplateId = $('.redCashPayAccountTemplateId').val(); //子账号ID

            if(!redCashCouponName) return layer.msg('请输入红包名称！');
            if(!redCashPrizeMsg) return layer.msg('请输入红包描述信息！');
            if(!redCashTotalMoney) return layer.msg('请输入红包总金额！');
            if(!redCashStartTime) return layer.msg('请选择红包开始时间！');
            if(!redCashEndTime) return layer.msg('请输选择红包结束时间！');
            if(!redCashPayAccountTemplateId) return layer.msg('为获取到子账号ID, 请重新操作！');

            if(isNaN(redCashTotalMoney) || redCashTotalMoney * 1 <= 0) return layer.msg('请输入正确的金额！');
            if(isNaN(redCashSingleMaxMoney) || redCashSingleMaxMoney * 1 <= 0) return layer.msg('请输入正确的金额！');

            var mgrUserIds = [];
            $.each($('.selectUserDiv input[name="selectUserItem"]:checked'), function(){
                mgrUserIds.push($(this).val());
            });
            if(mgrUserIds.length <= 0 ){
                return layer.msg('请选择分账用户！');
            }

            var layerMsgId = layer.msg('正在调起支付宝接口...',{time: 0, shade: 0.3});

            //创建红包
            admin.req({
                type: 'get',
                url: layui.setter.baseUrl + '/alipayCash/create',
                data:{
                    accountTemplateId: redCashPayAccountTemplateId,
                    couponName: redCashCouponName,
                    prizeMsg: redCashPrizeMsg,
                    "ps[singleMaxMoney]": (redCashSingleMaxMoney * 100).toFixed(0),
                    totalMoney: redCashTotalMoney,
                    startTime: redCashStartTime,
                    endTime: redCashEndTime,
                    "ps[mgrUserIds]": JSON.stringify(mgrUserIds)
                },
                error: function(err){layer.close(layerMsgId);layer.alert(err);},
                success: function(res){

                    layer.close(layerMsgId);
                    if(res.data.isSuccess){ //创建成功
                        thisRedCashId = res.data.alipayCashId;
                        layer.close(thisLayerId);
                        var thisAlipayPayUrl = res.data.payUrl;
                        if(thisAlipayPayUrl && thisAlipayPayUrl.indexOf("goto\=")){
                            thisAlipayPayUrl = thisAlipayPayUrl.substring(thisAlipayPayUrl.indexOf("goto\=") + 5);
                        }
                        window.open(thisAlipayPayUrl);
                        thisLayerId = layer.open({ type: 1, closeBtn:false, area: ['500px', 'auto'], title: '等待支付', content: toPayHtml });
                    }else{
                        layer.close(thisLayerId);
                        layer.alert('创建红包失败，原因：['+res.data.errorMsg+']');
                    }
                }
            });
        });

        $("body").on('click', '.redCashPayFinishOrFail', function(){ //支付完成 / 支付遇到问题

            layer.close(thisLayerId); //关闭上一个弹层

            //正在查询状态。。。
            var layerMsgId = layer.msg('正在查询红包最新状态...',{time: 0, shade: 0.3});

            admin.req({
                type: 'get',
                url: layui.setter.baseUrl + '/alipayCash/updateAlipayStatus',
                data: {cashId: thisRedCashId},
                error: function (err) {
                    layer.close(layerMsgId);
                    layer.alert(err);
                },
                success: function (res) {

                    layer.close(layerMsgId);

                    var alipayState = "未知（查询失败）";
                    if(res.data == 'CREATED') alipayState = "已创建未打款";
                    if(res.data == 'PAID') alipayState = "已打款";
                    if(res.data == 'READY') alipayState = "活动已开始";
                    if(res.data == 'PAUSE') alipayState = "活动已暂停";
                    if(res.data == 'CLOSED') alipayState = "活动已结束";
                    if(res.data == 'SETTLE') alipayState = "活动已清算";


                    if(res.data != 'PAID' && res.data != 'READY'){
                        return layer.alert('当前红包最新状态为：【'+alipayState+'】, 您可以在[红包记录]菜单中重新查询或发起支付！');
                    }

                    //以下为 支付宝状态为： 已打款 | 已开始

                    //弹层显示【立马发红包】
                    layer.confirm('您已支付完成，并且红包状态为可用，是否立即下发发红包？', {
                        btn: ['发红包','返回']
                    }, function(){
                        //请等待，正在创建【发红包】任务
                        layerMsgId = layer.msg('请等待，正在创建[发红包]任务... ',{time: 0, shade: 0.3});
                        admin.req({
                            type: 'get',
                            url: layui.setter.baseUrl + '/alipayCash/tiggerAlipayCash',
                            data: {cashId: thisRedCashId},
                            error: function (err) {
                                layer.close(layerMsgId);
                                layer.alert(err);
                            },
                            success: function (res) {

                                layer.close(layerMsgId);
                                if(res.code == '0'){ //成功创建任务
                                    layer.alert('任务创建完成，您可以在[红包记录]菜单中查看最新进度');
                                }else{ //任务创建失败
                                    layer.alert(res.errMsg);
                                }
                            }
                        });
                    });
                }
            });
        });

        form.on('checkbox(selectAllUserFilter)', function(data){
            $('.selectUserDiv input[name="selectUserItem"]').prop('checked', data.elem.checked);
            form.render();
        });

        form.on('checkbox(selectUserItemFilter)', function(data){
            $('.selectUserDiv input[lay-filter="selectAllUserFilter"]').prop('checked', false);
            form.render();
        });

        form.on('checkbox(redCashChangeSingleMaxMoneyFilter)', function(data){
            if(data.elem.checked){
                $('.redCashSingleMaxMoney').removeAttr('readonly').removeClass("layui-bg-gray");
            }else{
                $('.redCashSingleMaxMoney').attr('readonly', 'readonly').addClass("layui-bg-gray");
            }
        });

        // 搜索
        var $ = layui.$, active = {
            reload: function(){
                //执行重载
                table.reload('tableReload', {
                    page: {curr: 1}  //重新从第 1 页开始
                });
            }
        };
        $('#search').on('click', function() {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        // 渲染表单
        form.render();

    });

</script>
